package com.topisv.tms.utils.print;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.taobao.api.domain.WaybillApplyNewInfo;
import com.taobao.api.response.WlbWaybillIGetResponse;
import com.taobao.api.response.WlbWaybillIPrintResponse;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Consignor;
import com.topisv.tms.entity.CustomerAreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EcCorePrintRegion;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.ExpressStyle;
import com.topisv.tms.entity.LogisticsMailNo;
import com.topisv.tms.entity.PackformStyle;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.entity.YTOShortAddress;
import com.topisv.tms.entity.taobao.TopWaybillNoGetDto;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.mybatis.SqlMapDao;
import com.topisv.tms.repository.ExpressConfigureDao;
import com.topisv.tms.repository.YTOShortAddressDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.ConsignorService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EcCorePrintRegionService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ExpressStyleService;
import com.topisv.tms.service.LogisticsMailNoService;
import com.topisv.tms.service.PackformStyleService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.WarehouseAddressService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.vo.CNPrinterModel;
import com.topisv.tms.service.vo.CNPrinterStyleType;
import com.topisv.tms.service.vo.PackItems;
import com.topisv.tms.service.vo.PackStyleModel;
import com.topisv.tms.service.vo.PrinterModel;
import com.topisv.tms.service.vo.PrinterStyleType;
import com.topisv.tms.service.vo.yunda.OrderResponse;
import com.topisv.tms.service.vo.yunda.OrderResponses;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.service.yunda.YUNDAService;
import com.topisv.tms.service.zto.ZTOEbillService;
import com.topisv.tms.utils.ExpressRule;
import com.topisv.tms.utils.FileOperation;
import com.topisv.tms.utils.PrintModelUtil;
import com.topisv.tms.utils.PubUtil;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.WmsContants;
import com.topisv.tms.utils.bsht.MailBSHTUtil;
import com.topisv.tms.utils.bsht.vo.BillPrintDetailRsp;
import com.topisv.tms.utils.ems.EmsUtil;
import com.topisv.tms.utils.ems.getExpressNo.EmsAssignIds;
import com.topisv.tms.utils.ems.getExpressNo.EmsResponse;
import com.topisv.tms.utils.ems.sendPrintData.EmsPrintDataRequest;
import com.topisv.tms.utils.ems.sendPrintData.EmsPrintDataResponse;
import com.topisv.tms.utils.ems.sendPrintData.EmsPrintDatasRequest;
import com.topisv.tms.utils.ems.sendPrintData.EmsXMLInfoRequest;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.rfd.MailRFDUtil;
import com.topisv.tms.utils.sf.MailSFUtil;
import com.topisv.tms.utils.sto.MailSTOUtil;
import com.topisv.tms.utils.taobao.TopClientUtils;
import com.topisv.tms.utils.ttkd.DayMailSendRequest;
import com.topisv.tms.utils.yto.YTOMailUtil;
import com.topisv.tms.utils.yto.YTOResponse;
import com.topisv.tms.webservice.soap.sf.vo.CreateSFVO;

@Component
public class PickPrintUtil {

	protected Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ConsignorService consignorService;
	
	@Autowired
	private CustomersService customersService;

	@Autowired
	private PackformStyleService packformStyleService;
	
	@Autowired
	private PickUtil pickUtil;
	@Autowired
	private ExpressStyleService expressStyleService;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	@Autowired
	private EdiGoodsSkuService ediGoodsskuService;
	@Autowired
	private WarehouseAddressService warehouseAddressService;
	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private LogisticsMailNoService logisticsMailNoService;
	@Autowired
	private EcCorePrintRegionService ecCorePrintRegionService;
	@Autowired
	private YTOShortAddressDao ytoShortAddressDao;
	@Autowired
	private YUNDAService yundaService;
	@Autowired
	private ZTOEbillService ztoEbillService;
	
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private ExpressConfigureDao expressConfigureDao;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	@Autowired
    public SqlMapDao sqlMapDao;
	/**
	 * 打印电子面单方法
	 * @param ordenos
	 * @param expressId
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public  List<PrinterStyleType> printExpress(String ordenos ,Long expressId,String workCode)throws Exception{
		//EMS取单号存的
		EmsResponse emsResponse = null;
		log.info("printExpress--begin:ordenos="+ordenos+";expressId="+expressId+";workCode="+workCode);
		List<PrinterStyleType> printerStyleTypes = new ArrayList<PrinterStyleType>();
		ExpressStyle expressStyle=null;
		WorkOrder workOrder=null;
		try {
			PrinterStyleType p=null;
			expressStyle=expressStyleService.findOne(expressId);
			List<EdiOrder>  ediOrders=getShippedOrder(ordenos);
			WarehouseAddress wha = warehouseAddressService.findByWarehouseCode(ediOrders.get(0).getWarehouseCode());
			WorkTask workTask=this.workTaskService.loadTaskByCode(workCode);
			int length=ediOrders.size();
			if("HTKY".equals(expressStyle.getLogisticsCompany().getCompanyCode())){
				ExpressConfigure expressConfigure = null;
				if(ediOrders!=null&&ediOrders.size()>0){
					expressConfigure = expressConfigureDao.findByWarehouseAndCompany(ediOrders.get(0).getWarehouseCode(), "HTKY");
				}
					for(EdiOrder eo : ediOrders){
						List<BillPrintDetailRsp> rsps= MailBSHTUtil.mailNoRequest(eo, expressConfigure,wha);
						if(rsps==null||rsps.size()==0){
							log.info("=============汇通取号失败===============");
							return printerStyleTypes;
						}
						for(BillPrintDetailRsp rsp: rsps){
							String orderno = rsp.getTxLogisticID();
							String mailno = rsp.getMailNo();		//面单号
							String markDestination = rsp.getMarkDestination();	//大头笔
							String pkgCode = rsp.getPkgCode();		//集包编码
							String billProvideSiteName = rsp.getBillProvideSiteName();	//运单发放站点
							if(orderno.equals(eo.getOrdeno())){
								workOrder=workOrderService.loadOrder(eo.getBatchTaskCode(), eo.getOrdeno());
								//设置打印状态，写入快递单号数据
								this.workOrderService.setPrintStatus(workOrder.getOrder().getOrdeno(),mailno,expressStyle.getLogisticsCompany().getCompanyCode());
								eo.setMailNo(mailno);
								log.info("printExpress--workCode:"+workCode+";orderno="+eo.getOrdeno()+";mailno:"+mailno);
								eo.setToShortAddress(markDestination);
								eo.setRemark(pkgCode);
								eo.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
								eo.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
								eo.setShmemo(billProvideSiteName);
								p=getPrinterStyleType(eo,expressStyle);
								printerStyleTypes.add(p);
							}
						}
					}
			}
			else if("EMS".equals(expressStyle.getLogisticsCompany().getCompanyCode()))
			{
				ExpressConfigure expressConfigure = null;
				if(ediOrders!=null&&ediOrders.size()>0){
					expressConfigure = expressConfigureDao.findByWarehouseAndCompany(ediOrders.get(0).getWarehouseCode(), "EMS");
				}
				if(expressConfigure==null||StringUtils.isEmpty(expressConfigure.getAccount())||StringUtils.isEmpty(expressConfigure.getPassword())){
					log.info("EMS账号密码获取失败：");
					return printerStyleTypes;
				}
				emsResponse = EmsUtil.getExpressNo(length+"",expressConfigure.getAccount(),expressConfigure.getPassword(),expressConfigure.getUrl());
				if("0".equals(emsResponse.getResult())){
					log.info("EMS取号失败："+emsResponse.getErrorDesc());
					return printerStyleTypes;
				}
				List<EmsAssignIds> aisList = emsResponse.getAssignIds();
				
				EmsXMLInfoRequest info = new EmsXMLInfoRequest();
				info.setPrintKind("2");
				List<EmsPrintDatasRequest> printDatas = new ArrayList<EmsPrintDatasRequest>();
				for(int i = 0 ; i < aisList.size();i++) {
					EmsAssignIds assignIds = aisList.get(i);
					String billNo = assignIds.getAssignId().getBillno();//取出获取的单号
					EdiOrder ediOrder = ediOrders.get(i);
					workOrder=workOrderService.loadOrder(ediOrder.getBatchTaskCode(), ediOrder.getOrdeno());
//					List<EdiOrderItem> eois = ediOrderItemService.findByOrdeno(ediOrder.getOrdeno());
					WarehouseAddress warehouseAddres = warehouseAddressService.findByWarehouseCode(ediOrder.getWarehouseCode());
					
					EmsPrintDatasRequest pd = new EmsPrintDatasRequest();
					EmsPrintDataRequest printData = new EmsPrintDataRequest();
					printData.setBigAccountDataId(ediOrder.getOrdeno());
					printData.setBillno(billNo);
					printData.setScontactor(warehouseAddres.getContact());
					printData.setScustMobile(warehouseAddres.getMobile());
					printData.setScustPost("");
					printData.setScustAddr(warehouseAddres.getAddress());
					printData.setScustComp("上海派联仓储管理有限公司");
					printData.setTcontactor(ediOrder.getRecena());
					printData.setTcustMobile(ediOrder.getMobile());
					printData.setTcustTelplus(ediOrder.getTeleph());
					printData.setTcustPost("");
					printData.setTcustAddr(ediOrder.getAddres());
					printData.setTcustComp("");
					printData.setTcustProvince(ediOrder.getProvna());
					printData.setTcustCity(ediOrder.getCityna());
					printData.setTcustCounty(ediOrder.getDistna());
					printData.setWeight("");
					printData.setLength("");
					printData.setInsure("");
					printData.setCargoType("");
					printData.setRemark("");
					pd.setPrintData(printData);
					printDatas.add(pd);
					
					//注释掉,此处会导致更新work_order,打单和拣货同时进行时,work_order的status会冲突
					//workOrder.setEbillNo(billNo);
					//设置打印状态，写入快递单号数据
					this.workOrderService.setPrintStatus(workOrder.getOrder().getOrdeno(),billNo,expressStyle.getLogisticsCompany().getCompanyCode());
					ediOrder.setMailNo(billNo);
					log.info("printExpress--workCode:"+workCode+";orderno="+ediOrder.getOrdeno()+";mailno:"+billNo);
					ediOrder.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
					ediOrder.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
					
					p=getPrinterStyleType(ediOrder,expressStyle);
					printerStyleTypes.add(p);	
					
				}
				info.setPrintDatas(printDatas);
				EmsPrintDataResponse e = EmsUtil.sendExpressNo(info,expressConfigure.getAccount(),expressConfigure.getPassword(),expressConfigure.getUrl());
				log.info(e.getResult()+"|"+e.getErrorDesc());
				
			}else if("ZTO".equals(expressStyle.getLogisticsCompany().getCompanyCode())){
			    printerStyleTypes =  ztoEbillService.getZTOOrderAndMailno(ediOrders, workTask, expressStyle);
			} /*else if(StringUtils.equals("TTKDEX", expressStyle.getLogisticsCompany().getCompanyCode())) {
				
				ExpressConfigure expressConfigure = null;
				if(ediOrders!=null&&ediOrders.size()>0){
					expressConfigure = expressConfigureDao.findByWarehouseAndCompany(ediOrders.get(0).getWarehouseCode(), "TTKDEX");
				}
					
				//	long begin = (System.currentTimeMillis());
					for(EdiOrder eo : ediOrders){
						Map<String, String> resultMap = DayMailSendRequest.SendFaceBillMessage(expressConfigure,eo);
						if(resultMap==null||resultMap.size()==0){
							return printerStyleTypes;
						}
							String mailno = resultMap.get("key");		//运单号
							String result = resultMap.get("result");		//大头笔
							String packageCode = resultMap.get("packageCode");	//包编号
							String destCode = resultMap.get("package");		//打包区域 
							if(mailno.equals(eo.getMailNo())){
								workOrder=workOrderService.loadOrder(eo.getBatchTaskCode(), eo.getOrdeno());
								//设置打印状态，写入快递单号数据
								this.workOrderService.setPrintStatus(workOrder.getOrder().getOrdeno(),mailno,expressStyle.getLogisticsCompany().getCompanyCode());
								eo.setMailNo(mailno);
								eo.setDestCode(destCode);
								eo.setOriginCode(result);
								eo.setRemark(packageCode);
								eo.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
								eo.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
								p=getPrinterStyleType(eo,expressStyle);
								printerStyleTypes.add(p);
						}
					}
			}*/
			else {
				for(int i=0;i<length;i++){
					EdiOrder o=ediOrders.get(i);
					String printInfo = null;
					log.info("printExpress--workCode:"+workCode+";orderno="+o.getOrdeno()+"beforesynchronized");
					synchronized (this) {
						workOrder=workOrderService.loadOrder(o.getBatchTaskCode(), o.getOrdeno());
						if(workOrder.getEbillNo()==null||"cbill".equals(workOrder.getBillType())||
								"YUNDA".equals(expressStyle.getLogisticsCompany().getCompanyCode())||
								!expressStyle.getLogisticsCompany().getCompanyCode().equals(workOrder.getExpressCompany())){
							String mailNo = "";
							if("SF".equals(expressStyle.getLogisticsCompany().getCompanyCode()))
							{
								List<EdiOrderItem> eois = ediOrderItemService.findByOrdeno(o.getOrdeno());
//								if(eois.isEmpty())
//								{
//									log.info(o.getOrdeno()+"=====多件订单暂时无法使用顺丰电子面单");
//									return printerStyleTypes;
//								}
								List<EdiGoodsSku> skuList = new ArrayList<EdiGoodsSku>();
								for(EdiOrderItem item : eois)
								{
									EdiGoodsSku ediGoodsSku=ediGoodsskuService.findByCustomerCodeAndSku(o.getCustomerCode(), item.getSku());
//									if(null == ediGoodsSku)
//									{
//										log.info(o.getOrdeno()+"=====没有重量配置，无法使用顺丰电子面单");
//										return printerStyleTypes;
//									}
									skuList.add(ediGoodsSku);
								}
								WarehouseAddress warehouseAddress = warehouseAddressService.findByWarehouseCode(workOrder.getWarehouseCode());
								
								CreateSFVO createSFVO = MailSFUtil.getSFMailNo(o,skuList,expressStyle.getBarCode(),warehouseAddress);
								if("ERR".equals(createSFVO.getHeadText()))
								{
									log.info(o.getOrdeno()+"=====获取顺丰面单号失败===" + createSFVO.getCode() + "--" + createSFVO.getErrorText() );
									return printerStyleTypes;
								}
								else
								{
									if("3".equals(createSFVO.getFilterResult()))
									{
										log.info(o.getOrdeno()+"=====顺丰超区，不派送===");
										return printerStyleTypes;
									}
									if(createSFVO.getMailno()==null || "".equals(createSFVO.getMailno()))
									{
										log.info(o.getOrdeno()+"=====顺丰电子面单号为空===");
										return printerStyleTypes;
									}
									mailNo = createSFVO.getMailno();
									if("3".equals(expressStyle.getBarCode()))
									{
										workOrder.setExpressName("电商特惠");
									}
									else if("7".equals(expressStyle.getBarCode()))
									{
										workOrder.setExpressName("电商速配");
									}else if("1".equals(expressStyle.getBarCode())){
										workOrder.setExpressName("标准快递");
									}else if("2".equals(expressStyle.getBarCode())){
										workOrder.setExpressName("顺丰特惠");
									}else{
										workOrder.setExpressName(expressStyle.getBarCode());
									}
									workOrderService.save(workOrder);
									o.setDestCode(createSFVO.getDestcode());
									o.setOriginCode(createSFVO.getOrigincode());
								}
							}else if ("BJRFD-001".equals(expressStyle.getLogisticsCompany().getCompanyCode()))
							{
								List<EdiOrderItem> eois = ediOrderItemService.findByOrdeno(o.getOrdeno());
								if(eois.isEmpty())
								{
									log.info(o.getOrdeno()+"=====多件订单暂时无法使用如风达电子面单");
									return printerStyleTypes;
								}
								List<EdiGoodsSku> skuList = new ArrayList<EdiGoodsSku>();
								for(EdiOrderItem item : eois)
								{
									EdiGoodsSku ediGoodsSku=ediGoodsskuService.findByCustomerCodeAndSku(o.getCustomerCode(), item.getSku());
									if(null == ediGoodsSku)
									{
										log.info(o.getOrdeno()+"=====没有重量配置，无法使用如风达电子面单");
										return printerStyleTypes;
									}
									skuList.add(ediGoodsSku);
								}
								WarehouseAddress warehouseAddress = warehouseAddressService.findByWarehouseCode(workOrder.getWarehouseCode());
								String  result= MailRFDUtil.getRFDMailNo(o,skuList,warehouseAddress);
								if("".equals(result))
								{
									log.info(o.getOrdeno()+"=====获取不到如风达电子面单号");
									return printerStyleTypes;
								}
								else
								{
									JSONObject json = JSONObject.fromObject(result);
									if(json.getBoolean("IsSuccess"))
									{
										JSONArray jarray = json.getJSONArray("ResultData");
										JSONObject jObject = jarray.getJSONObject(0);
										mailNo = jObject.getString("WaybillNo");
										String SiteNo = jObject.getString("SiteNo");
										String CityNumber = jObject.getString("CityNumber");
										String StationName = jObject.getString("StationName");
										CityNumber = (CityNumber==null || "null".equals(CityNumber))?"":CityNumber;
										StationName = (StationName==null || "null".equals(StationName))?"":StationName;
										SiteNo = (SiteNo==null || "null".equals(SiteNo))?"":SiteNo;
										o.setDestCode(SiteNo);
										o.setOriginCode(CityNumber);
										o.setRemark(StationName);
									}
									else
									{
										log.info(o.getOrdeno()+"=====获取不到如风达电子面单号2");
										return printerStyleTypes;
									}
								}
							}
						else if("YUNDA".equals(expressStyle.getLogisticsCompany().getCompanyCode())){
							List<EdiOrderItem> eois = ediOrderItemService.findByOrdeno(o.getOrdeno());
							workOrder.getOrder().setOrderItems(eois);
							OrderResponses orderResponses = yundaService.createYunDaOrder(workOrder);
							if (orderResponses != null) {
								List<OrderResponse> responses = orderResponses.getOrderResponse();
								if (responses != null && !responses.isEmpty()) {
									OrderResponse response = responses.get(0);
									String status = response.getStatus();
									if ("0".equals(status)) {
										log.error(new StringBuilder().append(response.getOrderSerialNo()).append("|").append(response.getMsg()).toString());
										throw new Exception(new StringBuilder().append(response.getOrderSerialNo()).append("打印失败,因为:").append(response.getMsg()).toString());
									} else {
										mailNo = response.getMailNo();
										printInfo = response.getPdfInfo();
									}
								}
							}
						}
						else if("JD".equals(expressStyle.getLogisticsCompany().getCompanyCode())){
							mailNo=o.getMailNo();
						} else if("YTO".equals(expressStyle.getLogisticsCompany().getCompanyCode())) {
							//圆通电子面单
							ExpressConfigure expressConfigure = expressConfigureDao.findByWarehouseAndCompany(workTask.getWarehouseCode(), "YTO");
//								ResponseMessageVO rm= YTOMailUtil.postYTO(eo,wha,expressConfigure);
							YTOResponse rm= YTOMailUtil.postYTO(o,wha,expressConfigure);
							if(rm==null||!rm.getSuccess().equals("true")){
								log.info("=============创建圆通面单失败===============");
								return printerStyleTypes;
							}
							mailNo = rm.getOrderMessage().getMailNo();
							workOrder=workOrderService.loadOrder(o.getBatchTaskCode(), o.getOrdeno());
							//下面的方法重复调用 导致重复数据，暂时注释
							//设置打印状态，写入快递单号数据
							//this.workOrderService.setPrintStatus(workOrder.getOrder().getOrdeno(),rm.getOrderMessage().getMailNo(),expressStyle.getLogisticsCompany().getCompanyCode());
							o.setMailNo(mailNo);
							o.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
							if(rm.getOrderMessage() != null && rm.getOrderMessage().getBigPen() != null) {
								o.setToShortAddress(rm.getOrderMessage().getBigPen());
							}
						}
						else{
							List<LogisticsMailNo> logisticsMailNos=logisticsMailNoService.getLogisticsMailNo("pending", expressStyle.getLogisticsCompany().getCompanyCode(), workTask.getWarehouseCode(), 1);
							if(logisticsMailNos.isEmpty()){
								//没有电子面单号了
								log.info(expressStyle.getLogisticsCompany().getCompanyName()+"===网点=="+workTask.getWarehouseCode()+"没有电子面单号了");
								throw new Exception(expressStyle.getLogisticsCompany().getCompanyName()+"没有电子面单号了,请联系仓库负责人");
							}
							LogisticsMailNo lmo=logisticsMailNos.get(0);
							mailNo=lmo.getMailNo();
							if(StringUtils.equals("TTKDEX", expressStyle.getLogisticsCompany().getCompanyCode())) {
								ExpressConfigure expressConfigure = null;
								expressConfigure = expressConfigureDao.findByWarehouseAndCompany(workTask.getWarehouseCode(), "TTKDEX");
								if(expressConfigure != null)
								{
									Map<String, String> resultMap = DayMailSendRequest.SendFaceBillMessage(expressConfigure,o);
									if(resultMap!=null && resultMap.size()!=0){
										String result = resultMap.get("result");		//大头笔
										String packageCode = resultMap.get("packageCode");	//包编号
										String destCode = resultMap.get("package");		//打包区域 
										//设置打印状态，写入快递单号数据
										//eo.setMailNo(mailno);
										o.setDestCode(destCode);
										o.setOriginCode(result);
										o.setRemark(packageCode);
									}
								}
							}else if(StringUtils.equals("STO", expressStyle.getLogisticsCompany().getCompanyCode())) {
								ExpressConfigure expressConfigure = null;
								expressConfigure = expressConfigureDao.findByWarehouseAndCompany(workTask.getWarehouseCode(), "STO");
								if(expressConfigure != null)
								{
									//for(EdiOrder eo : ediOrders){
									    o.setMailNo(mailNo);
										String data= MailSTOUtil.sendOrderInfoForPrint(o,expressConfigure);
										if(data==null){
											log.info("=============申通取大头笔失败===============");
											return printerStyleTypes;
										}else{
											log.info("=============申通取大头笔==" + data);
											data=data.substring(1, data.lastIndexOf("]"));
											JSONObject  jasonObject = JSONObject.fromObject(data); 
											//Map map = (Map)jasonObject; 
											//eo.setToShortAddress(map.get("bigchar").toString());
											o.setDestCode(jasonObject.getString("bigchar").toString());
										}
										
									//}
								}
							}
						}
//						workOrder.setEbillNo(mailNo);
						//设置打印状态，写入快递单号数据
						log.info("printExpress:1--workCode="+workCode);
						this.workOrderService.setPrintStatus(workOrder.getOrder().getOrdeno(),mailNo,expressStyle.getLogisticsCompany().getCompanyCode());
						log.info("printExpress:2--workCode="+workCode);
						o.setMailNo(mailNo);
						log.info("printExpress--workCode:"+workCode+";orderno="+o.getOrdeno()+";mailno:"+mailNo);
						o.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
						o.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
						}else{
							log.info("printExpress:3--workCode="+workCode);
							this.workOrderService.setPrintStatus(workOrder.getOrder().getOrdeno(),workOrder.getEbillNo(),workOrder.getExpressCompany());
							log.info("printExpress:4--workCode="+workCode);
							log.info("printExpress--workCode:"+workCode+";orderno="+workOrder.getOrder().getOrdeno()+";mailno:"+workOrder.getEbillNo());
						}
						
					}
					log.info("printExpress:ordenos="+ordenos+";expressId="+expressId+";workCode="+workCode);
					log.info("printExpress--workCode:"+workCode+";orderno="+o.getOrdeno()+"aftersynchronized");
					p=getPrinterStyleType(o,expressStyle);
					//如果已经生成了打印内容 直接获取
					if (StringUtils.isNotBlank(printInfo)) {
						p.setContent(printInfo);
					}
					printerStyleTypes.add(p);	
				}
			}
			log.info("printExpress--end:ordenos="+ordenos+";expressId="+expressId+";workCode="+workCode);
			return printerStyleTypes;
		} catch (Exception e) {e.printStackTrace();
			log.error("printExpress--workCode:"+ workCode + "--" + e);
			throw e;
		}
		
	}
	
	
	/**
	 * 打印电子面单--使用淘宝开放平台
	 * @param ordenos
	 * @param expressId
	 * @param workCode
	 * @return List<PrinterStyleType>
	 * @throws Exception 
	 */
	/*@Transactional(readOnly = false)
	public List<CNPrinterStyleType> printExpressNew(String ordenos, Long expressId, String workCode) throws Exception {
		try {
			List<CNPrinterStyleType> printerStyleTypes = new ArrayList<CNPrinterStyleType>();
			ExpressStyle expressStyle = expressStyleService.findOne(expressId);
			TopWaybillNoGetDto waybillDto = new TopWaybillNoGetDto();
			ShopSource shopSource = shopSourceService.findByShopCode(WmsContants.SHOP_CODE_CN);
			*//**begin add 20160722 获取仓库信息 zhangweize*//*
			Map<String, WarehouseAddress> warehouseAddressMap = queryWarehouseAddress(workCode);
			*//**end add 20160722 获取仓库信息 zhangweize*//*
			if(warehouseAddressMap == null){
				throw new RuntimeException("找不到该商家与仓库的对应关系!");
			}
			String[] lists=ordenos.split(":");
			for (int i = 0; i < lists.length; i++) {
				WorkOrder workOrder = workOrderService.loadOrderByOrderno(lists[i]);
				*//**begin remove 20160722  zhangweize*//*
				//根据订单中仓库编码的查询仓库地址，并放到Map
//				WarehouseAddress warehouseAddress=warehouseAddressService.findByWarehouseCode(workOrder.getWarehouseCode());
//				warehouseAddressMap.put(warehouseAddress.getWarehouseCode(), warehouseAddress);
				*//**end remove 20160722  zhangweize*//*
				waybillDto.add(workOrder, shopSource, expressStyle.getLogisticsCompany().getCompanyCode());
			}
			
			//获取菜鸟面单
			List<WlbWaybillIGetResponse> wlbWaybillGetResponses = TopClientUtils.topGetWaybillNoBatch(waybillDto,warehouseAddressMap);
			log.info("菜鸟获取单号_wlbWaybillGetResponses:"+wlbWaybillGetResponses);
			for (WlbWaybillIGetResponse wlbWaybillIGetResponse : wlbWaybillGetResponses) {
				if(!StringUtils.isBlank(wlbWaybillIGetResponse.getErrorCode())){
					log.error("msg:{}|errorcode:{}|subcode:{}|submsg:{}",wlbWaybillIGetResponse.getMsg(),wlbWaybillIGetResponse.getErrorCode(),wlbWaybillIGetResponse.getSubCode(),wlbWaybillIGetResponse.getSubMsg());
					throw new RuntimeException("打印失败:"+wlbWaybillIGetResponse.getMsg()+":"+wlbWaybillIGetResponse.getSubMsg());
				}else{
					List<WaybillApplyNewInfo> results = wlbWaybillIGetResponse.getWaybillApplyNewCols();
					if(!results.isEmpty()){
						for (WaybillApplyNewInfo waybillApplyNewInfo : results) {
							String waybillNo = waybillApplyNewInfo.getWaybillCode();
							String orderNO = waybillApplyNewInfo.getTradeOrderInfo().getPackageId();
							WorkOrder workOrder = TopClientUtils.getEdiOrder(waybillDto, orderNO);
							EdiOrder ediOrder = workOrder.getOrder();
							ediOrder.setToShortAddress(waybillApplyNewInfo.getShortAddress());
							ediOrder.setMailNo(waybillNo);
							ediOrder.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
							ediOrder.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
							workOrderService.setPrintStatus(orderNO, waybillNo, expressStyle.getLogisticsCompany().getCompanyCode());
							CNPrinterStyleType p = getPrinterStyleTypeNew(ediOrder, expressStyle,waybillApplyNewInfo);
							printerStyleTypes.add(p);
						}
					}
				}
			}
			//校验print接口
//			List<WlbWaybillIPrintResponse> printCheckResponses = TopClientUtils.printCheck(waybillDto);
			List<WlbWaybillIPrintResponse> printCheckResponses = TopClientUtils.printCheckNew(waybillDto,warehouseAddressMap);
			log.info("菜鸟打印校验接口_printCheckResponses:"+printCheckResponses);
			for (WlbWaybillIPrintResponse wlbWaybillIPrintResponse : printCheckResponses) {
				if(!StringUtils.isBlank(wlbWaybillIPrintResponse.getErrorCode())){
					log.error("waybillCode:{}|msg:{}|errorcode:{}|subcode:{}|submsg:{}",wlbWaybillIPrintResponse.getErrorWaybillCode(),wlbWaybillIPrintResponse.getMsg(),wlbWaybillIPrintResponse.getErrorCode(),wlbWaybillIPrintResponse.getSubCode(),wlbWaybillIPrintResponse.getSubMsg());
					throw new RuntimeException("printCheck case some error:"+wlbWaybillIPrintResponse.getMsg()+":"+wlbWaybillIPrintResponse.getSubMsg());
				}
			}
			Collections.sort(printerStyleTypes);
			return printerStyleTypes;
		} catch (Exception e) {
			throw e;
		}
	}*/
	
	/**获取仓库信息
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @param taskCode 任务号
	 * @return
	 */
	@SuppressWarnings("unchecked")
    private Map<String,WarehouseAddress> queryWarehouseAddress(String taskCode){
		Map<String, WarehouseAddress> warehouseAddressMap = new HashMap<String, WarehouseAddress>();
		//根据任务号查询商家仓库表的记录
		List<CustomerAreaGroup> list = PubUtil.convertListMapToObject(
				sqlMapDao.selectList("customerAreaGroupMapper.getCustomerAreaByTaskCode", taskCode),CustomerAreaGroup.class);
		if (list == null || list.isEmpty()) {
			return null;
		}
		CustomerAreaGroup customerAreaGroup = list.get(0);
		// 根据订单中仓库编码的查询仓库地址，并放到Map
		WarehouseAddress warehouseAddress = warehouseAddressService
				.findByWarehouseCode(customerAreaGroup.getAreaGroupCode());
		WarehouseAddress tempWarehouseAddress = new WarehouseAddress();
		BeanUtils.copyProperties(warehouseAddress, tempWarehouseAddress);
		//cainiaoAddressStatus等于1表示不用仓库信息，寄件人、寄件人电话使用管理发货人中的名称和电话;否则使用仓库信息
		if ("1".equals(customerAreaGroup.getCainiaoAddressStatus())) {
			List<Consignor> consignorList = PubUtil.convertListMapToObject(
					sqlMapDao.selectList("consignorMapper.getConsignorByCustomerCode", customerAreaGroup),Consignor.class);
			if (consignorList == null || consignorList.isEmpty()) {
				tempWarehouseAddress.setContact("");
				tempWarehouseAddress.setMobile("");
			}else{
				tempWarehouseAddress.setContact(consignorList.get(0).getName());
				tempWarehouseAddress.setMobile(consignorList.get(0).getMobile());
			}
		}
		warehouseAddressMap.put(warehouseAddress.getWarehouseCode(),tempWarehouseAddress);
		return warehouseAddressMap;
	}
	@Transactional(readOnly = false)
	public List<PrinterStyleType> printExpress(String queues ,Long expressId)throws Exception{
		List<PrinterStyleType> printerStyleTypes = new ArrayList<PrinterStyleType>();
		ExpressStyle expressStyle=null;
		try {
			PrinterStyleType p=null;
			expressStyle=expressStyleService.findOne(expressId);
			List<EdiOrder> ediOrders=getEdiOrder(queues);
			for(EdiOrder o:ediOrders){
				o.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
            	o.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
				p=getPrinterStyleType(o,expressStyle);
				printerStyleTypes.add(p);
			}
			return printerStyleTypes;
		} catch (Exception e) {
			throw e;
		}
	}
	
	
	private List<EdiOrder> getEdiOrder(String queues)throws Exception{
		 List<EdiOrder>  ediOrders=new ArrayList<EdiOrder>();
		try {
			String[] lists=queues.split(":");
			for(String o:lists){
				if("".equals(o)){
					continue;
				}
				String[] values=o.split("==");
				String ordeno=values[0];//订单号
				String express=values[1];//快递单号
				String rankno=values[2];//打印顺序
				EdiOrder so=ediOrderService.findByOrdeno(ordeno);
				so.setMailNo(express);
				so.setRankno(rankno);
				ediOrders.add(so);
			}
			return ediOrders;
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 根据订单号打印快递单
	 * @param ordenos
	 * @param firstExpress
	 * @param expressId
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public List<PrinterStyleType> printExpress(String ordenos ,String firstExpress,Long expressId)throws Exception{
		List<PrinterStyleType> printerStyleTypes = new ArrayList<PrinterStyleType>();
		ExpressStyle expressStyle=null;
		try {
			PrinterStyleType p=null;
			expressStyle=expressStyleService.findOne(expressId);
			List<EdiOrder>  ediOrders=getShippedOrder(ordenos);
			for(EdiOrder o:ediOrders){
				//WorkOrder workOrder=workOrderService.loadOrder(o.getBatchTaskCode(), o.getOrdeno());
				//workOrder.setExpressCompany(expressStyle.getLogisticsCompany().getCompanyCode());//设置快递公司编码
				//设置打印状态，写入快递单号数据
				o.setMailNo(firstExpress);
				o.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
            	o.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
				p=getPrinterStyleType(o,expressStyle);
				printerStyleTypes.add(p);
				firstExpress=ExpressRule.getExpress(expressStyle.getLogisticsCompany().getCompanyCode(),firstExpress);

			}
			return printerStyleTypes;
		} catch (Exception e) {
			throw e;
		}
	}
	
	
	
	
	/**
	 * 根据拣货任务号打印快递单
	 * 获得快递单的打印信息
	 * @param workId
	 * @param firstExpress
	 * @param expressId
	 * @return
	 * @throws Exception
	 */
	public List<PrinterStyleType> printExpress(Long workId,String firstExpress,Long expressId)throws Exception{
		List<PrinterStyleType> printerStyleTypes = new ArrayList<PrinterStyleType>();
		ExpressStyle expressStyle=null;
		try {
			PrinterStyleType p=null;
			expressStyle=expressStyleService.findOne(expressId);
			WorkTask workTask=workTaskService.loadTaskById(workId);
			List<WorkOrder>  workOrders=workOrderService.findByTaskCode(workTask.getTaskCode());
			for(WorkOrder w:workOrders){
				WorkOrder workOrder=this.workOrderService.loadByExpressNo(firstExpress);
				if(workOrder!=null){
					throw new Exception("快递单号:"+firstExpress+"重复使用");
				}
				EdiOrder ediOrder=ediOrderService.findByOrdeno(w.getOrder().getOrdeno());
				ediOrder.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
				ediOrder.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
				//w.setExpressCompany(expressStyle.getLogisticsCompany().getCompanyCode());//设置快递公司编码
				//设置打印状态，写入快递单号数据
				p=getPrinterStyleType(ediOrder,expressStyle);
				printerStyleTypes.add(p);
				firstExpress=ExpressRule.getExpress(expressStyle.getLogisticsCompany().getCompanyCode(),firstExpress);

			}
			return printerStyleTypes;
		} catch (Exception e) {
			throw e;
		}
	}
	
	private PrinterStyleType getPrinterStyleType(EdiOrder ediOrder,ExpressStyle expressStyle)throws Exception{
		try {
			PrinterModel printerModel = new PrinterModel();
			getExpressStyleModel(printerModel,ediOrder);
			return getPrinterStyleType(printerModel,expressStyle);
		} catch (Exception e) {e.printStackTrace();
			throw e;
		}
	}
	private CNPrinterStyleType getPrinterStyleTypeNew(EdiOrder ediOrder,ExpressStyle expressStyle,WaybillApplyNewInfo applyInfo)throws Exception{
		try {
			CNPrinterModel pm= new CNPrinterModel();
			getExpressStyleModel(pm,ediOrder);
			//设置菜鸟字段
			pm.setShortAddress(applyInfo.getShortAddress());
			//电话设置到一个字段内
			if (StringUtils.isBlank(pm.getToPhone())) {
				pm.setToPhone(pm.getToMobile());
			} else if (!StringUtils.isBlank(pm.getToMobile()) && !pm.getToPhone().equals(pm.getToMobile())) {
				pm.setToPhone(new StringBuilder().append(pm.getToPhone()).append("   ").append(pm.getToMobile()).toString());
			}
			pm.setProductType(null);//产品类型
			pm.setPackageCenterName(applyInfo.getPackageCenterName());
			pm.setPackageCenterCode(applyInfo.getPackageCenterCode());
			pm.setShippingBranchName(applyInfo.getShippingBranchName());
			pm.setShippingBranchCode(applyInfo.getShippingBranchCode());
			pm.setExtSFBizType(null);
			pm.setShippingAddressCity(null);
			pm.setPrintConfig(applyInfo.getPrintConfig());
			/**begin remove 商品明细不要显示全部 bug498 byzhangweize*/
//			StringBuilder sb = new StringBuilder();
//			
//			for (EdiOrderItem item : ediOrder.getOrderItems()) {
//				sb.append(item.getSku()).append("(").append(item.getQty()).append(")\n");
//			}
//			pm.setProductName(sb.toString());
			/**end remove 商品明细不要显示全部 bug498 byzhangweize*/
			return getPrinterStyleTypeNew(pm,expressStyle);
		} catch (Exception e) {
			throw e;
		}
	}
	
	
	private List<PrinterStyleType> printPackForm(List<String> ordenos,PackformStyle packformStyle)throws Exception{
		List<PrinterStyleType> printerStyleTypes = new ArrayList<PrinterStyleType>();
		try {
			PrinterStyleType p=null;
			for (String o : ordenos) {
				String[] lists=o.split("==");
				if(lists.length==2){
					EdiOrder oo = ediOrderService.findByOrdeno(lists[0]);
					if (oo == null) {// 流水批次
                        throw new Exception("数据有误!");
					} 
					if(StatusEnums.SHIPPED_ORDER_STATUS_CANCEL.getStatus().equals(oo.getStatus())){
						//continue;
					}
					p=getPrinterStyleType(oo,lists[1],packformStyle);
				}else{
					WorkTask workTask=workTaskService.loadTaskById(Long.parseLong(o));
					p=getPrinterStyleType(workTask);
				}
				printerStyleTypes.add(p);
			}
			return printerStyleTypes;
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 根据订单号打印随箱单
	 * @param ordenos
	 * @param packformStyleId
	 * @return
	 * @throws Exception
	 */
	public List<PrinterStyleType> printPackForm(String ordenos,Long packformStyleId) throws Exception {
		try {
			List<EdiOrder>  ediOrders=getShippedOrder(ordenos);
			return printPackForm(ediOrders,packformStyleId);
		} catch (Exception e) {
			throw e;
		}
	}
	
	private List<PrinterStyleType> printPackForm(List<EdiOrder>  ediOrders,Long packformStyleId)throws Exception{
		List<PrinterStyleType> printerStyleTypes=new ArrayList<PrinterStyleType>();
		PackformStyle packformStyle=packformStyleService.findOne(packformStyleId);//获得随箱单的模版
		try {
			for(EdiOrder o:ediOrders){
				WorkOrder workOrder=workOrderService.loadOrder(o.getBatchTaskCode(), o.getOrdeno());
				PackStyleModel packStyleModel=getPackStyleModel(o, workOrder.getRankno()+"",packformStyle.getType());
				PrinterStyleType printerStyleType=getPrinterStyleType(packStyleModel, packformStyle);
				printerStyleTypes.add(printerStyleType);
			}
			return printerStyleTypes;
		} catch (Exception e) {
			throw e;
		}
	}
	
	private List<EdiOrder> getShippedOrder(String ordenos)throws Exception{
		 List<EdiOrder>  ediOrders=new ArrayList<EdiOrder>();
		try {
			String[] lists=ordenos.split(":");
			for(String o:lists){
				EdiOrder so=ediOrderService.findByOrdeno(o);
				ediOrders.add(so);
			}
			return ediOrders;
		} catch (Exception e) {
			throw e;
		}
	}
	
	
	/**
	 * 获得随箱单的打印信息
	 * @param workIds
	 * @param ordeno
	 * @param number
	 * @param packformStyleId
	 * @param sb
	 * @return
	 * @throws Exception
	 */
	public List<PrinterStyleType> printPackForm(String workIds,String ordeno,int number,Long packformStyleId,StringBuffer sb) throws Exception {
		try {
			PackformStyle packformStyle=packformStyleService.findOne(packformStyleId);//获得随箱单的模版
			List<String> ordenos=pickUtil.getOrdenos(workIds, ordeno, number,sb);//获得将要打印的随箱单快递单号
			return printPackForm(ordenos,packformStyle);
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 打印随箱单时分割打印任务
	 * @param workIds
	 * @param number
	 * @return
	 * @throws Exception
	 */
	public String packFormCount(String workIds,int number)throws Exception{
		try {
			StringBuffer sb=new StringBuffer("begin:");
			List<String> ordenos=pickUtil.getOrdenos(workIds);
			int count=ordenos.size();//打印的总张数
			count=count%number==0? count/number:(count/number)+1;//总页数
			for(int i=1;i<count;i++){
				int index=i*number-1;
				if("begin:".equals(sb.toString())){
					sb.append(ordenos.get(index));
				}else{
					sb.append(":"+ordenos.get(index));
				}
				
			}
			return sb.toString();
		} catch (Exception e) {
			throw e;
		}
	}
	
	public String expressCount(String workIds,int number,String firstExpress,Long expressId)throws Exception{
		try {
			
			StringBuffer sb=new StringBuffer("");
			List<String> ordenos=pickUtil.getOrdenos(workIds, firstExpress, expressId);
			int count=ordenos.size();//打印的总张数			
			for(int i=0;i<count;i++){
				if(i!=0&&i%number==0){
					sb.append(",");
				}
				if("".equals(sb.toString())){
					sb.append(ordenos.get(i));
				}else{
					sb.append(":"+ordenos.get(i));
				}
			}
			return sb.toString();
		} catch (Exception e) {
			throw e;
		}
	}

	
	
	/**
	 * 分隔页
	 * @return
	 * @throws Exception
	 */
	private PrinterStyleType getPrinterStyleType(WorkTask workTask)throws Exception{
		try {
			String content=getContent(workTask);
			PrinterStyleType printerStyleType = new PrinterStyleType();
			printerStyleType.setContent(content);//打印的html内容
			printerStyleType.setTaskName(workTask.getTaskCode());//打印任务名
			printerStyleType.setOrdeno("0");
			printerStyleType.setRankno(0);//打印的顺序
			return printerStyleType;
		} catch (Exception e) {
			throw e;
		}
		
	}
	/**
	 * 打印批次分隔页
	 * @return
	 * @throws Exception
	 */
	private String getContent(WorkTask workTask)throws Exception{
		StringBuffer sb=new StringBuffer();
		try {
			String lineType="";
			if("single".equals(workTask.getPickType())){
				lineType="单件";
			}else if("forward".equals(workTask.getPickType())){
				lineType="中转发";
			}else{
				lineType="多件";
			}
			sb.append("<div style='height:160mm; width:120mm; text-align:center;font-size:44px;border:8px solid #000000; font-weight:bold'>");
			
			sb.append("<span>"+workTask.getTaskCode()+"</span>");
			
			sb.append("<ul style='text-align:left; font-size:22px'>");
			sb.append("<li>类型："+lineType+"</li>");
			
			sb.append("<li>分拣批次："+workTask.getBatchCode()+"</li>");
			
			sb.append("<li>订单数量："+workTask.getOrderQty()+"</li>");
			
			sb.append("<li>商家编码："+workTask.getCustomerCode()+"</li>");
			
			
			sb.append("</ul>");
			sb.append("</div>");
			return sb.toString();
		} catch (Exception e) {
			throw e;
		}
	}
	
	@Autowired
	private AreaService areaService;
	
	/**
	 * 获得打印快递单所需要的信息
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	public <T extends PrinterModel> T getExpressStyleModel(T pm,EdiOrder ediOrder) throws UnsupportedEncodingException {

			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			if (null!=curUser) {
				pm.setOperator(curUser.username);
			}
			String ordeno = ediOrder.getOrdeno();
			Customers customers = customersService.findByCustomerCode(ediOrder.getCustomerCode());
			Consignor consignor = consignorService.findCustomersId(customers.getId());
			
			WorkTask workTask=this.workTaskService.loadTaskByCode(ediOrder.getBackupTaskCode());
			
			/*if("SF".equals(ediOrder.getCacode()))
			{*/
				pm.setDestCode(ediOrder.getDestCode());
			/*}else {
				//获取城市邮编的前三位数字
				Area areaProv = areaService.findByAreaName2(ediOrder.getProvna());
				if(areaProv!=null){
					Area areaCity = areaService.findByAreaNameAndParentId(ediOrder.getCityna(), areaProv.getId());
					if(areaCity!=null&&areaCity.getZipCode()!=null&&areaCity.getZipCode().length()>=3){
						pm.setDestCode(areaCity.getZipCode().substring(0,3));
					}
				}
			}*/
			pm.setOriginCode(ediOrder.getOriginCode());
			pm.setWaybillNo(ediOrder.getMailNo());
			// 收件人信息
			pm.setToAddress(ediOrder.getAddres().replace("\"", " "));
			pm.setToPhone(ediOrder.getTeleph());
			pm.setToName(ediOrder.getRecena());
			pm.setToMobile(ediOrder.getMobile());
			pm.setToProvince(ediOrder.getProvna());
			pm.setToCity(ediOrder.getCityna());
			pm.setToTowns(ediOrder.getDistna());
			pm.setDestination(ediOrder.getProvna());
			pm.setOrdeno(ordeno);
			pm.setToZipcode(ediOrder.getPostco());
			pm.setPayTime(TimeUtil.getNowDateStringDD(ediOrder.getCrtime()));
			pm.setFromno(ediOrder.getFromno());
			pm.setCustomerOrdeno(ediOrder.getCustomerOrdeno());
			
			// 商品信息
			pm.setPostFee(ediOrder.getPosfee() + "");
			pm.setAllCost(ediOrder.getActuallyPaid() + "");
			pm.setNumber(ediOrder.getSkuQty() + "");
			pm.setBunick(ediOrder.getBunick());//会员昵称
			pm.setExpressNo(ediOrder.getMailNo());
			
			pm.setCompanyCode(ediOrder.getCacode());
			pm.setCompanyName(ediOrder.getCaname());
			pm.setShopName(ediOrder.getShopna());
			pm.setBz(ediOrder.getRemark());
			pm.setBillProvideSiteName(ediOrder.getShmemo());	//运单发放站点
			//pm.setDestination(ediOrder.getRemark());
 
			//大头笔
			pm.setToDistCode(ediOrder.getToShortAddress());
			YTOShortAddress ytoShortAddress = ytoShortAddressDao.findShortAddress(ediOrder.getProvna(), ediOrder.getCityna(), ediOrder.getDistna(), ediOrder.getCacode());
			pm.setShortAddress(ytoShortAddress == null ? ediOrder.getCityna() : ytoShortAddress.getShortAddress());
			//设置仓库地址
			WarehouseAddress warehouseAddress = warehouseAddressService.findByWarehouseCode(ediOrder.getWarehouseCode());
			StringBuilder stringBuilder=new StringBuilder();
			if (warehouseAddress != null) {
				pm.setWarehouseAddress(
						stringBuilder.append(warehouseAddress.getProvName()).append(warehouseAddress.getCityName())
								.append(warehouseAddress.getDistName()).append(warehouseAddress.getAddress()).toString());
				pm.setWarehouseContact(warehouseAddress.getContact());
				pm.setWarehouseMobile(warehouseAddress.getMobile());
				CustomerAreaGroup customerWarehouse = customerAreaGroupService
						.findByCustomerCodeAndAreaGroupCode(ediOrder.getCustomerCode(), ediOrder.getWarehouseCode());
				if (customerWarehouse != null) {
					if ("1".equals(customerWarehouse.getCainiaoAddressStatus())) {
						pm.setWarehouseAddress(consignor.getAddress());
						pm.setWarehouseContact(consignor.getName());
						pm.setWarehouseMobile(consignor.getMobile());
					}
				}
	
			}
			WorkOrder workOrder = workOrderService.loadByAnyOrderno(ordeno);
			if(workOrder != null){
				pm.setTaskName(new StringBuilder().append(ediOrder.getBatchTaskCode()).append("_").append(ediOrder.getBackupTaskCode()).append("_").append(workTask.getOrderQty()).append("_").append(workOrder.getRankno()).append(workOrder.getPrintFlag()>0?"_C"+(workOrder.getPrintFlag()+1):"").toString());
				pm.setRankno(workOrder.getRankno());
				pm.setStockInfo(workOrder.getStockInfo());
				if("QRT".equals(workOrder.getExpressCompany())){
					if("广东省".equals(ediOrder.getProvna())){
					String address = pub("http://42.121.1.163:8888/geohash/getWord","province="+ediOrder.getProvna()+
							"&city="+ediOrder.getCityna()+"&district="+ediOrder.getDistna()+"&street="+ediOrder.getAddres());
					JSONObject json = JSONObject.fromObject(address);
					if(null != json && json.containsKey("data")){
						JSONObject data = JSONObject.fromObject(json.getString("data"));
						String zyshortAddress = data.getString("word");
						pm.setZyshortAddress(zyshortAddress);
					}
					}
				}
				
			}
			try {
				List<EcCorePrintRegion> ecCorePrintRegions=ecCorePrintRegionService.findByAreaName(ediOrder.getCityna());
				if(ecCorePrintRegions.isEmpty()){
					pm.setTitleName(ediOrder.getCityna());
				}else if(ecCorePrintRegions.size()==1){
					pm.setTitleName(ecCorePrintRegions.get(0).getTitleName());
				}else{
					EcCorePrintRegion ecCorePrintRegion=ecCorePrintRegionService.findByAreaNameAndLayers(ediOrder.getProvna(), 1);
					if(ecCorePrintRegion==null){
						pm.setTitleName(ediOrder.getCityna());
					}else{
						for(EcCorePrintRegion epr:ecCorePrintRegions){
							if(epr.getFullName().indexOf(ediOrder.getProvna())==0){
								pm.setTitleName(epr.getTitleName());
								break;
							}else{
								pm.setTitleName(ediOrder.getCityna());
							}
						}
					}
				}
			} catch (Exception e) {
				
			}
			
			List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(ediOrder.getCustomerCode(), ordeno);
			List<PackItems> packItems = new ArrayList<PackItems>();
			int orderItems = ediOrderItems.size()>3?3:ediOrderItems.size();
			int tempTotol=0;//计算一个订单包含的商品总数
			
			/**add 打印菜鸟商品明细只显示前3条  bug498 byzhangweize*/
			StringBuilder sb = new StringBuilder();
			
			for (int j = 0; j < orderItems; j++) {
				EdiOrderItem ediOrderItem = ediOrderItems.get(j);
				PackItems packItem = new PackItems();
				packItem.setPrice(ediOrderItem.getPri() + "");
				packItem.setPay(ediOrderItem.getPay() + "");
				packItem.setDis(ediOrderItem.getDis() + "");
				packItem.setAmo(ediOrderItem.getAmo() + "");
				packItem.setNumber(ediOrderItem.getQty() + "");
				tempTotol+=ediOrderItem.getQty();
				packItem.setItemName(ediOrderItem.getNam());
				packItem.setPromotion(ediOrderItem.getPro() + "");
				packItem.setFormat(ediOrderItem.getSiz());
				packItem.setSkuNumber(ediOrderItem.getSku());// 货号
				packItem.setItemCode(ediOrderItem.getSku());// 货号
				packItem.setArticleNumber(ediOrderItem.getArticleNumber());
				packItems.add(packItem);
				
				/**add 打印菜鸟商品明细只显示前3条  bug498 byzhangweize*/
				sb.append(ediOrderItem.getSku()).append("(").append(ediOrderItem.getQty()).append(") | ");
				
			}
			if(ediOrderItems.size()>3){
				for(int j=3;j<ediOrderItems.size();j++){
					EdiOrderItem ediOrderItem = ediOrderItems.get(j);
					tempTotol+=ediOrderItem.getQty();
				}
					/**add 打印菜鸟商品明细只显示前3条,大于3条的用省略号代替  bug498 byzhangweize*/
				sb.append("......");
			}
			pm.setTotalSkuNumber(tempTotol+"");
			pm.setPackItems(packItems);
			
			/**add 打印菜鸟商品明细只显示前3条  bug498 byzhangweize*/
			pm.setProductName(sb.toString());

			String weight = "";
			String length = "";//长度 cm
			String width = ""; //宽 cm
			String height = "";//高 cm
			if(workOrder != null)
			{
				float _weight=0;
				for(EdiOrderItem item : ediOrderItems)
				{
					EdiGoodsSku ediGoodsSku=ediGoodsskuService.findByCustomerCodeAndSku(workOrder.getCustomerCode(), item.getSku());
					if(null == ediGoodsSku)
					{
						continue;
					}
					_weight += (ediGoodsSku.getWeight()==null?0:ediGoodsSku.getWeight())+(ediGoodsSku.getWeightPkg()==null?0:ediGoodsSku.getWeightPkg());
					if("single".equals(ediOrder.getOrderType()) && "MID".equals(workOrder.getCustomerCode()))
					{
						length = Float.parseFloat(ediGoodsSku.getLen())/10 + "cm";
						width = Float.parseFloat(ediGoodsSku.getWid())/10 + "cm";
						height = Float.parseFloat(ediGoodsSku.getHei())/10 + "cm";
					}
					if("multiple".equals(ediOrder.getOrderType()) && "MID".equals(workOrder.getCustomerCode()))
					{
						if("1".equals(ediGoodsSku.getSellFlg()))
						{
							length = Float.parseFloat(ediGoodsSku.getLen())/10 + "cm";
							width = Float.parseFloat(ediGoodsSku.getWid())/10 + "cm";
							height = Float.parseFloat(ediGoodsSku.getHei())/10 + "cm";
						}
					}
				}
				weight = _weight/1000 + "kg";
				pm.setWeight(weight);
				pm.setLength(length);
				pm.setWidth(width);
				pm.setHeight(height);
				
			}
			
			// 寄件人信息
			if(consignor!=null){
				pm.setFromAddress(consignor.getAddress());
				pm.setFromName(consignor.getName());
				pm.setFromPhone(consignor.getPhone());
				pm.setFromMobile(consignor.getMobile());
				pm.setFromCompany(consignor.getAddress());
				pm.setOrigin(consignor.getDistrict());
				pm.setFromZipcode(consignor.getZipcode());
				pm.setFromCity(consignor.getCity());
				pm.setFromTowns(consignor.getDistrict());
			}
			return pm;
		
	}



	/**
	 * 获得打印随箱单所需要的信息
	 * 
	 * @param index
	 * @return
	 * @throws Exception
	 */
	private PackStyleModel getPackStyleModel(EdiOrder ediOrder,String index,String... stockFlag) throws Exception {
		try {
			StringBuffer total = new StringBuffer();
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String ordeno = ediOrder.getOrdeno();
			WorkOrder workOrder=workOrderService.loadOrder(ediOrder.getBatchTaskCode(), ordeno);
			Customers customers = customersService.findByCustomerCode(ediOrder.getCustomerCode());
			Consignor consignor = consignorService.findCustomersId(customers.getId());
			
			PackStyleModel packStyleModel = new PackStyleModel();
			if (consignor != null) {
				packStyleModel.setSalesRerurnAddress(consignor.getSalesRerurnAddress());// 退货地址
				packStyleModel.setSalesRerurnMessage(consignor.getSalesRerurnMessage());// 退货提醒
				packStyleModel.setCustomerName(consignor.getCustomers().getCustomerName());
				packStyleModel.setCustomerCode(workOrder.getCustomerCode());
				packStyleModel.setCustomerDesignation(consignor.getCustomers().getCustomerName());
				packStyleModel.setDepositoryName(consignor.getDepositoryName());
				packStyleModel.setSalesRerurnPhone(consignor.getPhone());
			}
			List<PackItems> packItems = new ArrayList<PackItems>();
			List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(ediOrder.getCustomerCode(), ordeno);
			
			/* add LiBin 20161215 bug628随箱单增加库位显示↓*/
			//当随箱单模板配置了A4的类型，就是打印带库位的随箱单，否则打印不带库位的随箱单(即之前的流程)。
			//由于随箱单中的模板类型不起作用，这里拿来使用。主要防止有的客户不要库位显示，留一手
			if(StringUtils.isBlank(workOrder.getStockInfo())){
			    stockFlag[0]="A4";
			}
			if (null != stockFlag && "A4".equals(stockFlag[0])) {
			    setPackItemsWithStock(workOrder.getStockInfo().split(";"),ediOrderItems, ediOrder, packItems, total);
			}else {
			    setPackItems(ediOrderItems, ediOrder, packItems, total);
            }
			/* add LiBin 20161215 bug628随箱单增加库位显示↑*/
			
			packStyleModel.setCustomerOrdeno(ediOrder.getCustomerOrdeno());
			packStyleModel.setFromno(ediOrder.getFromno());
			packStyleModel.setTaskName(ediOrder.getBatchTaskCode()+"_"+ediOrder.getBackupTaskCode()+"_" + index);
			packStyleModel.setTaskNameNew(ediOrder.getBatchTaskCode()+"_"+ediOrder.getBackupTaskCode()+"_" + index);
			packStyleModel.setPackItems(packItems);
			packStyleModel.setAllTotal(ediOrder.getActuallyPaid() + "");
			//packStyleModel.setPhone(StringUtils.isBlank(ediOrder.getTeleph())?ediOrder.getMobile():ediOrder.getTeleph());
			//update by LiBin 2016/07/13 获取电话和手机字段
			packStyleModel.setPhone(StringUtils.isBlank(ediOrder.getMobile())?"":"null".equals(ediOrder.getMobile().toLowerCase())?"":ediOrder.getMobile());//手机
			packStyleModel.setTeleph(StringUtils.isBlank(ediOrder.getTeleph())?"":"null".equals(ediOrder.getTeleph().toLowerCase())?"":ediOrder.getTeleph());//电话
			packStyleModel.setProvna(ediOrder.getProvna());
			packStyleModel.setCityna(ediOrder.getCityna());
			packStyleModel.setDistna(ediOrder.getDistna());
			packStyleModel.setSememo(ediOrder.getSememo());
			packStyleModel.setNumber(ediOrder.getSkuQty() + "");
			packStyleModel.setStoreName("".equals(ediOrder.getShopna())?customers.getCustomerName():ediOrder.getShopna());
			packStyleModel.setBumemo(ediOrder.getBumemo());
			packStyleModel.setNowDate(TimeUtil.getNowDateStringDD());
			packStyleModel.setPayDate(TimeUtil.getNowDateStringDD(ediOrder.getCrtime()));
			packStyleModel.setOrdeno(ediOrder.getOrdeno());
			packStyleModel.setLogisticalCode(workOrder.getExpressName());
			packStyleModel.setRankno(Integer.parseInt(index));
			packStyleModel.setAddress(ediOrder.getAddres().replace(" ", ""));// 收货人地址
			packStyleModel.setBunick(ediOrder.getBunick());
			packStyleModel.setReceiverName(ediOrder.getRecena());
			if("cbill".equals(workOrder.getBillType())){
				packStyleModel.setLogisticalBill(workOrder.getExpressNo());
			}else{
				packStyleModel.setLogisticalBill(workOrder.getEbillNo());
			}
			if (null!=curUser) {
				packStyleModel.setOperator(curUser.realname);
			}
			AreaGroup areaGroup= areaGroupService.findByGroupCode(workOrder.getWarehouseCode());
			if(null!=areaGroup){
				//packStyleModel.setWarehouseName(workOrder.getWarehouse().getGroupName());
				packStyleModel.setWarehouseName(areaGroup.getGroupName());
			}
			packStyleModel.setTaskCode(workOrder.getTaskCode());
			if("".equals(ediOrder.getShopna())){
				if(!"".equals(ediOrder.getShopCode())){
					ShopSource shopSource=shopSourceService.findByShopCode(ediOrder.getShopCode());
					packStyleModel.setShopna(null==shopSource?"":shopSource.getShopName());
				}
			}else {
				packStyleModel.setShopna(ediOrder.getShopna());
			}
			packStyleModel.setCrtime(TimeUtil.getNowDateStringDD(ediOrder.getCrtime()));
			packStyleModel.setPosfee(ediOrder.getPosfee()+"");
			packStyleModel.setTotal(total.toString());
			packStyleModel.setOutime(TimeUtil.getNowDateString());
			packStyleModel.setPrintFormFlag((workOrder.getPrintFormFlag()+1)+"");
			packStyleModel.setBusinessBz(ediOrder.getRemark());
			packStyleModel.setTotalAmount(ediOrder.getTotalAmount()+"");

			return packStyleModel;
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 设置随箱单的商品明细资料(不打印库位)
	 * @param packItems 需要赋值的明细列表
	 * @param ediOrderItems 订单明细
	 * @param total 需要设置的总金额（暂时不优化）
	 * @return 
	 * @throws 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 1.0.0
	 */
	private void setPackItems(List<EdiOrderItem> ediOrderItems,EdiOrder ediOrder,List<PackItems> packItems,StringBuffer total){
	    Double temp = 0D;
	    for (int j = 0; j < ediOrderItems.size(); j++) {
            
            EdiOrderItem ediOrderItem = ediOrderItems.get(j);
            EdiGoodsSku ediGoodsSku= this.ediGoodsskuService.findBySkuAndCustomerCode(ediOrderItem.getSku(),ediOrder.getCustomerCode());
            PackItems packItem = new PackItems();
            packItem.setPrice(ediOrderItem.getPri() + "");
            packItem.setTagPrice(ediGoodsSku.getTagPrice());
            if(null!=ediOrderItem.getPay()){
                packItem.setPay(ediOrderItem.getPay() + "");
            }else {
                if(null!=ediOrderItem.getPri()&&null!=ediOrderItem.getQty()){
                    packItem.setPay(ediOrderItem.getPri()*ediOrderItem.getQty() + "");
                }
            }
            packItem.setDis(ediOrderItem.getDis() + "");
            Double amo = 0D;
            if("".equals(ediOrderItem.getAmo())||ediOrderItem.getAmo()==null){
                amo = ediOrderItem.getPri() == null ? 0 : ediOrderItem.getPri() * ediOrderItem.getQty();
            }else{
                amo=ediOrderItem.getAmo();
            }
            packItem.setAmo(amo + "");
            packItem.setNumber(ediOrderItem.getQty() + "");
            packItem.setItemName(StringUtils.isBlank(ediOrderItem.getNam())?ediGoodsSku.getSkuName():ediOrderItem.getNam());
            packItem.setPromotion(ediOrderItem.getPro() + "");
            packItem.setFormat(StringUtils.isBlank(ediOrderItem.getSiz())?ediGoodsSku.getSpec():ediOrderItem.getSiz());
            packItem.setSkuNumber(ediOrderItem.getSku());// 货号
            packItem.setItemCode(ediOrderItem.getSku());// 货号
            packItem.setArticleNumber(ediGoodsSku.getBar());
            packItem.setSku_gwt(ediGoodsSku.getWeight()+"");
            packItem.setSku_mem(ediGoodsSku.getWeightPkg()+"");
            packItem.setSku_len(ediGoodsSku.getLen());
            packItem.setSku_hei(ediGoodsSku.getHei());
            packItem.setSku_wid(ediGoodsSku.getWid());
            packItem.setBrandName(ediGoodsSku.getBrandName());
            packItem.setColor(ediGoodsSku.getCol());
            if(null!=ediOrderItem.getPri()&&null!=ediOrderItem.getQty()){
                temp += null!=ediOrderItem.getPay()&&ediOrderItem.getPay()>0?ediOrderItem.getPay():ediOrderItem.getPri()*ediOrderItem.getQty();
            }
            packItems.add(packItem);
        }
	    total.append(temp);
	}
	
	/**
     * 设置随箱单的商品明细资料(打印库位)
     * @param packItems 需要赋值的明细列表
     * @param ediOrderItems 订单明细
     * @param total 需要设置的总金额（暂时不优化）
     * @return 
     * @throws 
     * @author <a href=mailto:libin@nryuncang.com>libin</a>
     * @version 1.0.0
     */
    private void setPackItemsWithStock(String[] stockInfos,List<EdiOrderItem> ediOrderItems,EdiOrder ediOrder,List<PackItems> packItems,StringBuffer total){
        Double temp = 0D;
        for (int j = 0; j < stockInfos.length; j++) {
            String[] info = stockInfos[j].split("_");
            
            EdiOrderItem ediOrderItem = updateEdiorderItems(ediOrderItems).get(info[2]);
            EdiGoodsSku ediGoodsSku= this.ediGoodsskuService.findBySkuAndCustomerCode(ediOrderItem.getSku(),ediOrder.getCustomerCode());
            PackItems packItem = new PackItems();
            packItem.setPrice(ediOrderItem.getPri() + "");
            packItem.setTagPrice(ediGoodsSku.getTagPrice());
            if(null!=ediOrderItem.getPay() && ediOrderItem.getPay() > 0){
                packItem.setPay(ediOrderItem.getPay() + "");
            }else {
                if(null!=ediOrderItem.getPri()){
                    packItem.setPay(ediOrderItem.getPri()*Integer.parseInt(info[3]) + "");
                }
            }
            packItem.setDis(ediOrderItem.getDis() + "");
            Double amo = 0D;
            if(null == ediOrderItem.getAmo() || ediOrderItem.getAmo() == 0){
                amo = ediOrderItem.getPri() == null ? 0 : ediOrderItem.getPri() * Integer.parseInt(info[3]);
            }else{
                amo=ediOrderItem.getAmo();
            }
            packItem.setAmo(amo + "");
            packItem.setNumber(info[3]);
            packItem.setItemName(StringUtils.isBlank(ediOrderItem.getNam())?ediGoodsSku.getSkuName():ediOrderItem.getNam());
            packItem.setPromotion(ediOrderItem.getPro() + "");
            packItem.setFormat(StringUtils.isBlank(ediOrderItem.getSiz())?ediGoodsSku.getSpec():ediOrderItem.getSiz());
            packItem.setSkuNumber(ediOrderItem.getSku());// 货号
            packItem.setItemCode(ediOrderItem.getSku());// 货号
            packItem.setArticleNumber(ediGoodsSku.getBar());
            packItem.setSku_gwt(ediGoodsSku.getWeight()+"");
            packItem.setSku_mem(ediGoodsSku.getWeightPkg()+"");
            packItem.setSku_len(ediGoodsSku.getLen());
            packItem.setSku_hei(ediGoodsSku.getHei());
            packItem.setSku_wid(ediGoodsSku.getWid());
            packItem.setBrandName(ediGoodsSku.getBrandName());
            packItem.setColor(ediGoodsSku.getCol());
            packItem.setStockInfo(info[0]);
            if(null!=ediOrderItem.getPri()){
                temp += null!=ediOrderItem.getPay()&&ediOrderItem.getPay()>0?ediOrderItem.getPay():ediOrderItem.getPri()*Integer.parseInt(info[3]);
            }
            packItems.add(packItem);
        }
        total.append(temp);
    }
    
    /**
     * 按照sku合并订单明细
     * 合并金额
     * @param 
     * @return 
     * @throws 
     * @author <a href=mailto:libin@nryuncang.com>libin</a>
     * @version 1.0.0
     */
    private Map<String, EdiOrderItem> updateEdiorderItems(List<EdiOrderItem> ediOrderItems){
        Map<String, EdiOrderItem> tempMap = new HashMap<String, EdiOrderItem>();
        for (EdiOrderItem ediOrderItem : ediOrderItems) {
            String sku=ediOrderItem.getSku();
            if (tempMap.containsKey(sku)) {
                EdiOrderItem tempEdiOrderItem=(EdiOrderItem)tempMap.get(sku).clone();
                tempEdiOrderItem.setAmo(formatDouble(tempEdiOrderItem.getAmo()) + formatDouble(ediOrderItem.getAmo()));
                tempEdiOrderItem.setDis(formatDouble(tempEdiOrderItem.getDis()) + formatDouble(ediOrderItem.getDis()));
                tempEdiOrderItem.setPay(formatDouble(tempEdiOrderItem.getPay()) + formatDouble(ediOrderItem.getPay()));
                tempEdiOrderItem.setPro(formatDouble(tempEdiOrderItem.getPro()) + formatDouble(ediOrderItem.getPro()));
                tempMap.put(sku,tempEdiOrderItem);
            } else {
                tempMap.put(sku, ediOrderItem);
            }
        }
        return tempMap;
    }
    
    /**
     * @param 
     * @return 
     * @throws 
     * @author <a href=mailto:libin@nryuncang.com>libin</a>
     * @version 1.0.0
     */
    private Double formatDouble(Double aDouble){
        return null==aDouble?0:aDouble;
    }
    
	private PrinterStyleType getPrinterStyleType(PrinterModel printerModel,ExpressStyle expressStyle) throws Exception {
		String contentString = null;
		try {
			PrinterStyleType printerStyleType = new PrinterStyleType();
        	String expressContent = FileOperation.readerContent(expressStyle.getStyleContent());// 转化的时候
            if("normal".equals(expressStyle.getType())){
    			contentString = PrintModelUtil.replaceParams(expressContent,printerModel);
            }else if("mail".equals(expressStyle.getType())){
    			contentString = PackFormUtil.replaceParams(expressContent, printerModel);

            }
            contentString= contentString.replace("'", "\\'").replaceAll("\"", "'");
			printerStyleType.setContent(contentString);
			printerStyleType.setCompanyCode(expressStyle.getLogisticsCompany().getCompanyCode());
			printerStyleType.setCompanyName(expressStyle.getLogisticsCompany().getCompanyName());
			printerStyleType.setTaskName(printerModel.getTaskName());
			printerStyleType.setRankno(printerModel.getRankno());
			printerStyleType.setOrdeno(printerModel.getOrdeno());
			printerStyleType.setTime(printerModel.getPayTime());
			printerStyleType.setFromno(printerModel.getFromno());
			printerStyleType.setExpressNo(printerModel.getExpressNo()); //KK no
			return printerStyleType;
		} catch (Exception e) {
			throw e;
		}
	}
	private CNPrinterStyleType getPrinterStyleTypeNew(CNPrinterModel printerModel,ExpressStyle expressStyle) throws Exception {
		CNPrinterStyleType printerStyleType = new CNPrinterStyleType();
		printerStyleType.setCompanyCode(expressStyle.getLogisticsCompany().getCompanyCode());
		printerStyleType.setCompanyName(expressStyle.getLogisticsCompany().getCompanyName());
		printerStyleType.setTaskName(printerModel.getTaskName());
		printerStyleType.setRankno(printerModel.getRankno());
		printerStyleType.setOrdeno(printerModel.getOrdeno());
		printerStyleType.setTime(printerModel.getPayTime());
		printerStyleType.setFromno(printerModel.getFromno());
		printerStyleType.setExpressNo(printerModel.getExpressNo());
		printerStyleType.setCnPrinterModel(printerModel);
		printerStyleType.setContent(expressStyle.getStyleContent());
		printerStyleType.setRankno(printerModel.getRankno());
		return printerStyleType;
	}

	private PrinterStyleType getPrinterStyleType(PackStyleModel packStyleModel,PackformStyle packformStyle) throws Exception {

		try {
			PrinterStyleType printerStyleType = new PrinterStyleType();
			String content = PackFormUtil.replaceParams(packformStyle.getStyleContent(), packStyleModel);
			//add LiBin 增加随箱单LoGo的显示 20160810
            if (content.indexOf("<logos>") > 0 && content.indexOf("</logos>") > 0) {
                String logos = content.substring(content.indexOf("<logos>"), content.indexOf("</logos>") + 8);// 取出LoGo部分
                printerStyleType.setPrinterLoGo(logos.replace("<logos>", "").replace("</logos>", ""));// 打印LoGo的赋值，交给前台打印
                content = content.replace(logos, "");// 从打印内容中去除LoGo部分
            }
			printerStyleType.setContent(content);//打印的html内容
			printerStyleType.setTaskName(packStyleModel.getTaskName());//打印任务名
			printerStyleType.setOrdeno(packStyleModel.getOrdeno());//打印的订单号
			printerStyleType.setRankno(packStyleModel.getRankno());//打印的顺序
			printerStyleType.setTime(packStyleModel.getPayDate());//打印的时间
			printerStyleType.setExpressNo(packStyleModel.getLogisticalBill());
			printerStyleType.setCustomerCode(packStyleModel.getCustomerCode());
			return printerStyleType;
		} catch (Exception e) {
			throw e;
		}
	}

	private PrinterStyleType getOrdenoPrinterStyleType(EdiOrder ediOrder,String index,PackformStyle packformStyle)
			throws Exception {
		PrinterStyleType printerStyleType = new PrinterStyleType();
		try {
			PackStyleModel packStyleModel=getPackStyleModel(ediOrder,index,packformStyle.getType());
			printerStyleType =getPrinterStyleType(packStyleModel,packformStyle);
			return printerStyleType;
		} catch (Exception e) {
			throw e;
		}
	}

	private PrinterStyleType getPrinterStyleType(EdiOrder ediOrder,String index,PackformStyle packformStyle) throws Exception {
		PrinterStyleType printerStyleType = new PrinterStyleType();
		try {
			
			 printerStyleType=getOrdenoPrinterStyleType(ediOrder,index,packformStyle);
		
			return printerStyleType;
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * 根据size分割订单号
	 * @param taskCode
	 * @param size
	 * @return
	 */
	public String spliteEbillOrder(String taskCode, int size) {
		List<WorkOrder> orders = workOrderService.findByTaskCode(taskCode);
		StringBuilder sb = new StringBuilder();
		for (int i = 0, length = orders.size(); i < length; i++) {
			WorkOrder order = orders.get(i);
			sb.append(order.getOrder().getOrdeno()).append(":");
			if (i != 0 && i % size == 0) {
				sb.append(";");
			}
		}
		return sb.append(";finish").toString();
	}
	
	public String pub(String serviceURL, String param) {
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
		try {
			url = new URL(serviceURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Length",param.length()+"");
			//connection.setRequestProperty("Content-Type", "text/json;charset=utf-8");
			// connection.setRequestProperty("User-Agent","Java/1.6.0_29");
			//connection.connect();
			OutputStream os=connection.getOutputStream();
	        DataOutputStream dos=new DataOutputStream(os);
	        dos.write(param.getBytes("UTF-8"));
	        dos.flush();
	        dos.close(); 
			/*OutputStream outputStream = connection.getOutputStream();
			outputStream.write(param.getBytes("UTF-8"));
			outputStream.flush();
			outputStream.close();*/
			InputStream inputStream = connection.getInputStream();
			byte[] bytes = new byte[1024];
			int count = inputStream.read(bytes);
			while (count != -1) {
				buffer.append(new String(bytes, 0, count, "UTF-8"));
				count = inputStream.read(bytes);
			}
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}
}
